service.playSoundTick() service.speak("Welcome to the advanced AI Pro! Please wait.")
function launchTool(code)
require "import"
import "java.io.*"
service.setSharedData("tmp", package.searchpath("main",package.path):match("(.+)/main.lua"))
fl = "/sdcard/解说/Tools/tmp_ext/"
File(fl).mkdirs()
io.open(fl.."main.lua","w"):write(code):close()
task(1200,function() service.tool("tmp_ext") end)
task(2000,function() f = "/sdcard/解说/Tools/tmp_ext/main.lua" local file = File(f) if file.exists() then file.delete() else end end)
end
launchTool[[
require "import"
import "android.widget.*"
import "android.view.*"
import "android.speech.tts.*"
import "android.content.*"
import "android.app.*"
import "java.util.Locale"
import "android.preference.PreferenceManager"
import "android.net.Uri"
import "java.io.File"
import "java.io.FileInputStream"
import "java.io.FileOutputStream"
import "java.io.ObjectInputStream"
import "java.io.ObjectOutputStream"
import "java.io.*"
import "java.net.URL"
import "java.io.InputStream"
import "android.graphics.BitmapFactory"
import "android.graphics.*"
import "org.json.JSONObject"
import "android.os.AsyncTask"
import "android.text.*"
import "android.content.Context"
import "android.speech.SpeechRecognizer"
import "android.speech.RecognitionListener"
import "android.speech.RecognizerIntent"
import "android.speech.tts.TextToSpeech"
import "android.content.*"
import "android.graphics.Color"
import "cjson"
import "java.text.SimpleDateFormat"
import "java.util.Date"
import "java.io.*"
function exit()
activity.finish()
end
context = activity or service
local tts
local sharedPrefs = activity.getSharedPreferences("TTS_Prefs", Context.MODE_PRIVATE)
local defaultEngine = sharedPrefs.getString("engine", nil)
local defaultLanguageCode = sharedPrefs.getString("language", "en")
local defaultSpeed = tonumber(sharedPrefs.getString("speed", "1.0"))
local defaultPitch = tonumber(sharedPrefs.getString("pitch", "1.0"))
tts = TextToSpeech(activity, TextToSpeech.OnInitListener {
onInit = function(status)
if status == TextToSpeech.SUCCESS then
if defaultEngine then
tts.setEngineByPackageName(defaultEngine)
end
tts.setLanguage(Locale(defaultLanguageCode))
tts.setSpeechRate(defaultSpeed)
tts.setPitch(defaultPitch)
end
end
})
function speakText(text)
tts.speak(text, TextToSpeech.QUEUE_FLUSH, nil, nil)
end
function stopTTS()
tts.stop()
end
messages = {}
function showToast(message)
speakText(message)
end
function urlEncode(text)
text = tostring(text)
text = text:gsub("\n", "\r\n")
text = text:gsub("([^%w %-%_%.%~])", function(c)
return string.format("%%%02X", string.byte(c))
end)
text = text:gsub(" ", "+")
return text
end
function cleanText(text)
local success, result = pcall(cjson.decode, text)
if success and result then
return result.message or "Text is not available."
else
return "Text is not available."
end
end
function copyToClipboard(text)
local clipboard = activity.getSystemService(Context.CLIPBOARD_SERVICE)
local clip = ClipData.newPlainText("Copied Text", text)
clipboard.setPrimaryClip(clip)
showToast("Text copied to clipboard!")
end
function addMessage(messagesContainer, title, message)
local sdf = SimpleDateFormat("hh:mm a")
local currentDate = Date()
local time = sdf.format(currentDate)
local fullMessage = title .. " " .. message .. " " .. time
local textView = TextView(activity)
messagesContainer.addView(textView)
textView.setText(fullMessage)
table.insert(messages, fullMessage)
textView.setTextColor(0xFFFFFFFF)
textView.setTextSize(16)
textView.setGravity(Gravity.CENTER_VERTICAL)
textView.setTextIsSelectable(true)
textView.setOnLongClickListener(View.OnLongClickListener{
onLongClick = function(view)
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
local popupMenu = PopupMenu(activity, view)
popupMenu.menu.add("Copy")
popupMenu.menu.add("Share")
popupMenu.menu.add("Read aloud")
popupMenu.menu.add("Delete Message")
popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener {
onMenuItemClick = function(item)
text = textView.getText()
if item.getTitle() == "Copy" then
copyToClipboard(text)
elseif item.getTitle() == "Share" then
local intent = Intent(Intent.ACTION_SEND)
intent.setType("text/plain")
intent.putExtra(Intent.EXTRA_TEXT, text)
activity.startActivity(Intent.createChooser(intent, "Share via"))
elseif item.getTitle() == "Read aloud" then
speakText(text)
elseif item.getTitle() == "Delete Message" then
AlertDialog.Builder(activity)
.setTitle("Delete Message")
.setMessage("Are you sure you want to delete this message?")
.setPositiveButton("Yes", DialogInterface.OnClickListener{
onClick = function(dialog, which)
messagesContainer.removeView(view)
for i, msg in ipairs(messages) do
if msg == fullMessage then
table.remove(messages, i)
break
end
end
saveMessages()
showToast("message deleted successfully!")
end
})
.setNegativeButton("No", nil)
.show()
end
return true
end
})
popupMenu.show()
return true
end
})
if message:match("```(.-)```") then
local copyCodeButton = Button(activity)
copyCodeButton.setText("Copy Code")
copyCodeButton.setOnClickListener(View.OnClickListener{
onClick = function(view)
local codes = {}
for code in string.gmatch(message, "```(.-)```") do
table.insert(codes, code)
end
if #codes > 0 then
local codeText = table.concat(codes, "\n")
copyToClipboard(codeText)
end
end
})
messagesContainer.addView(copyCodeButton)
end
if message == "AI is typing..." then
messagesContainer.removeViewAt(messagesContainer.getChildCount() - 1)
end
end
function saveMessages()
local prefs = activity.getSharedPreferences("ChatPrefs", Context.MODE_PRIVATE)
local editor = prefs.edit()
editor.putString("messages", table.concat(messages, "|"))
editor.apply()
end
function loadMessages()
local prefs = activity.getSharedPreferences("ChatPrefs", Context.MODE_PRIVATE)
local savedMessages = prefs.getString("messages", "")
messages = {}
if savedMessages ~= "" then
for message in savedMessages:gmatch("[^|]+") do
table.insert(messages, message)
end
end
end
function showPreviousMessages()
local listView = ListView(activity)
local adapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1, messages)
listView.setAdapter(adapter)
listView.setOnItemLongClickListener(AdapterView.OnItemLongClickListener {
onItemLongClick = function(parent, view, position, id)
text = messages[position + 1]
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
local popupMenu = PopupMenu(activity, view)
popupMenu.menu.add("Copy")
popupMenu.menu.add("Share")
popupMenu.menu.add("Read aloud")
popupMenu.menu.add("Delete Message")
popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener {
onMenuItemClick = function(item)
if item.getTitle() == "Copy" then
copyToClipboard(text)
elseif item.getTitle() == "Share" then
local intent = Intent(Intent.ACTION_SEND)
intent.setType("text/plain")
intent.putExtra(Intent.EXTRA_TEXT, text)
activity.startActivity(Intent.createChooser(intent, "Share via"))
elseif item.getTitle() == "Read aloud" then
speakText(text)
elseif item.getTitle() == "Delete Message" then
AlertDialog.Builder(activity)
.setTitle("Delete Message")
.setMessage("Are you sure you want to delete this message?")
.setPositiveButton("Yes", DialogInterface.OnClickListener{
onClick = function(dialog, which)
for i, msg in ipairs(messages) do
if msg == text then
table.remove(messages, i)
break
end
end
adapter.clear()
adapter.addAll(messages)
adapter.notifyDataSetChanged()
saveMessages()
showToast("message deleted successfully!")
end
})
.setNegativeButton("No", nil)
.show()
end
return true
end
})
popupMenu.show()
return true
end
})
local dialogLayout = LinearLayout(activity)
dialogLayout.setOrientation(LinearLayout.VERTICAL)
dialogLayout.addView(listView, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1))
AlertDialog.Builder(activity)
.setTitle("Chat History")
.setView(dialogLayout)
.setPositiveButton("Clear Chat History", function()
AlertDialog.Builder(activity)
.setTitle("Clear Chat History?")
.setMessage("Are you sure you want to clear all chat history?")
.setPositiveButton("Yes", DialogInterface.OnClickListener{
onClick = function(dialog, which)
messages = {}
saveMessages()
adapter.notifyDataSetChanged()
showToast("Chat history deleted successfully!")
end
})
.setNegativeButton("No", nil)
.show()
end)
.setNegativeButton("Close", nil)
.setNeutralButton("Share History", function()
local data = ""
for i = 0, adapter.getCount() - 1 do
data = data .. adapter.getItem(i) .. "\n"
end
local intent = Intent(Intent.ACTION_SEND)
intent.setType("text/plain")
intent.putExtra(Intent.EXTRA_TEXT, data)
activity.startActivity(Intent.createChooser(intent, "Share via"))
end)
.show()
end
function onCreate(sis)
activity.setTitle("Advance AI Pro.")
activity.setTheme(android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen)
local mainLayout = LinearLayout(activity)
mainLayout.setOrientation(LinearLayout.VERTICAL)
mainLayout.setBackgroundColor(0xFF1E1E1E)
moreOptionButton = Button(activity)
moreOptionButton.setText("•\n•\n•")
moreOptionButton.setGravity(Gravity.LEFT)
moreOptionButton.setTextSize(40)
moreOptionButton.setTextColor(0xFFFFFFFF)
moreOptionButton.setContentDescription("More options")
local params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.gravity = Gravity.TOP | Gravity.LEFT
moreOptionButton.setLayoutParams(params)
moreOptionButton.setOnClickListener(View.OnClickListener{
onClick = function(view)
local popupMenu = PopupMenu(activity, view)
popupMenu.menu.add("TTS announcement settings")
popupMenu.menu.add("Clear Chat")
popupMenu.menu.add("Chat History")
popupMenu.menu.add("Developers")
popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener {
onMenuItemClick = function(item)
if item.getTitle() == "TTS announcement settings" then
local function savePreference(key, value)
local prefs = activity.getSharedPreferences("TTS_Prefs", Context.MODE_PRIVATE)
local editor = prefs.edit()
editor.putString(key, value)
editor.apply()
end
local function getPreference(key, defaultValue)
local prefs = activity.getSharedPreferences("TTS_Prefs", Context.MODE_PRIVATE)
return prefs.getString(key, defaultValue)
end
local function getTextToSpeechEngines()
local TextToSpeechClass = luajava.bindClass("android.speech.tts.TextToSpeech")
local tts = TextToSpeechClass(activity.getApplicationContext(), nil)
local availableEngines = {}
local enginesList = tts.getEngines()
if enginesList ~= nil then
for i = 0, enginesList.size() - 1 do
local engine = enginesList.get(i)
table.insert(availableEngines, {name = engine.label, package = engine.name})
end
end
return availableEngines, tts
end
local availableEngines, tts = getTextToSpeechEngines()
if #availableEngines > 0 then
local layout = LinearLayout(activity)
layout.setOrientation(LinearLayout.VERTICAL)
warningTextView = TextView(activity)
warningTextView.setTextSize(14)
warningTextView.setTextColor(Color.RED)
warningTextView.setText("Warning:\nIf you set up the TTS announcement settings but it doesn't work properly, please restart the extension and try again!")
layout.addView(warningTextView)
local engineDialogButton = Button(activity)
engineDialogButton.setText("Select TTS Engine, Currently selected: "..getPreference("engine", "Default"))
engineDialogButton.setOnClickListener(function(view)
local engineDialog = AlertDialog.Builder(activity)
engineDialog.setTitle("Select TTS Engine")
local radioGroup = RadioGroup(activity)
for _, engine in ipairs(availableEngines) do
local radioButton = RadioButton(activity)
radioButton.setText(engine.name)
radioGroup.addView(radioButton)
if engine.package == getPreference("engine", availableEngines[1].package) then
radioButton.setChecked(true)
end
end
local scrollView = ScrollView(activity)
scrollView.addView(radioGroup)
engineDialog.setView(scrollView)
engineDialog.setPositiveButton("OK", DialogInterface.OnClickListener{
onClick = function(dialog, which)
local checkedId = radioGroup.getCheckedRadioButtonId()
local selectedRadioButton = radioGroup.findViewById(checkedId)
if selectedRadioButton then
local selectedEngine = selectedRadioButton.getText()
for _, engine in ipairs(availableEngines) do
if engine.name == selectedEngine then
tts.setEngineByPackageName(engine.package)
tts.speak("Selected TTS: " .. engine.name, TextToSpeech.QUEUE_FLUSH, nil, "")
savePreference("engine", engine.package)
break
end
end
end
end
})
engineDialog.setNegativeButton("Cancel", nil)
engineDialog.show()
end)
layout.addView(engineDialogButton)
local languageCodes = {
["Afrikaans"] = "af",
["Akan"] = "ak",
["Albanian"] = "sq",
["Amharic"] = "am",
["Arabic"] = "ar",
["Armenian"] = "hy",
["Azerbaijani"] = "az",
["Basque"] = "eu",
["Belarusian"] = "be",
["Bengali"] = "bn",
["Bosnian"] = "bs",
["Bulgarian"] = "bg",
["Burmese"] = "my",
["Catalan"] = "ca",
["Cebuano"] = "ceb",
["Chinese"] = "zh",
["Corsican"] = "co",
["Croatian"] = "hr",
["Czech"] = "cs",
["Danish"] = "da",
["Dutch"] = "nl",
["English"] = "en",
["Esperanto"] = "eo",
["Estonian"] = "et",
["Faroese"] = "fo",
["Filipino"] = "tl",
["Finnish"] = "fi",
["French"] = "fr",
["Galician"] = "gl",
["Georgian"] = "ka",
["German"] = "de",
["Greek"] = "el",
["Gujarati"] = "gu",
["Haitian Creole"] = "ht",
["Hausa"] = "ha",
["Hawaiian"] = "haw",
["Hebrew"] = "he",
["Hindi"] = "hi",
["Hmong"] = "hmn",
["Hungarian"] = "hu",
["Icelandic"] = "is",
["Igbo"] = "ig",
["Indonesian"] = "id",
["Irish"] = "ga",
["Italian"] = "it",
["Japanese"] = "ja",
["Javanese"] = "jv",
["Kannada"] = "kn",
["Kazakh"] = "kk",
["Khmer"] = "km",
["Kinyarwanda"] = "rw",
["Korean"] = "ko",
["Kurdish"] = "ku",
["Kyrgyz"] = "ky",
["Lao"] = "lo",
["Latin"] = "la",
["Latvian"] = "lv",
["Lithuanian"] = "lt",
["Luxembourgish"] = "lb",
["Macedonian"] = "mk",
["Malagasy"] = "mg",
["Malay"] = "ms",
["Malayalam"] = "ml",
["Maltese"] = "mt",
["Maori"] = "mi",
["Marathi"] = "mr",
["Mongolian"] = "mn",
["Nepali"] = "ne",
["Norwegian"] = "no",
["Nyanja"] = "ny",
["Odia"] = "or",
["Pashto"] = "ps",
["Persian"] = "fa",
["Polish"] = "pl",
["Portuguese"] = "pt",
["Punjabi"] = "pa",
["Romanian"] = "ro",
["Russian"] = "ru",
["Samoan"] = "sm",
["Scots Gaelic"] = "gd",
["Serbian"] = "sr",
["Sesotho"] = "st",
["Shona"] = "sn",
["Sindhi"] = "sd",
["Sinhala"] = "si",
["Slovak"] = "sk",
["Slovenian"] = "sl",
["Somali"] = "so",
["Spanish"] = "es",
["Sundanese"] = "su",
["Swahili"] = "sw",
["Swedish"] = "sv",
["Tagalog"] = "tl",
["Tajik"] = "tg",
["Tamil"] = "ta",
["Tatar"] = "tt",
["Telugu"] = "te",
["Thai"] = "th",
["Turkish"] = "tr",
["Ukrainian"] = "uk",
["Urdu"] = "ur",
["Uyghur"] = "ug",
["Uzbek"] = "uz",
["Vietnamese"] = "vi",
["Welsh"] = "cy",
["Xhosa"] = "xh",
["Yiddish"] = "yi",
["Yoruba"] = "yo",
["Zulu"] = "zu"
}
local languageNames = {}
for name, code in pairs(languageCodes) do
table.insert(languageNames, name)
end
table.sort(languageNames)
local languageDialogButton = Button(activity)
local selectedLanguageIndex = -1
for i, name in ipairs(languageNames) do
if languageCodes[name] == getPreference("language", "en") then
selectedLanguageIndex = i - 1
break
end
end
languageDialogButton.setText("Language for voice conversation, Currently selected: "..languageNames[selectedLanguageIndex + 1])
languageDialogButton.setOnClickListener(function(view)
local languageDialog = AlertDialog.Builder(activity)
languageDialog.setTitle("Language for voice conversation")
languageDialog.setSingleChoiceItems(languageNames, selectedLanguageIndex, DialogInterface.OnClickListener{
onClick = function(dialog, which)
local selectedLanguage = languageNames[which + 1]
local languageCode = languageCodes[selectedLanguage]
tts.setLanguage(Locale(languageCode))
tts.speak("Selected language: " .. selectedLanguage, TextToSpeech.QUEUE_FLUSH, nil, "")
savePreference("language", languageCode)
dialog.dismiss()
end
})
languageDialog.setNegativeButton("Cancel", nil)
languageDialog.show()
end)
layout.addView(languageDialogButton)
local speedDialogButton = Button(activity)
speedDialogButton.setText("Select Speech Speed, Currently selected: "..getPreference("speed", "1.0"))
speedDialogButton.setOnClickListener(function(view)
local speedDialog = AlertDialog.Builder(activity)
speedDialog.setTitle("Select Speech Speed")
local speeds = {"0.5", "0.75", "1.0", "1.25", "1.5", "1.75", "2.0"}
local currentSpeed = getPreference("speed", "1.0")
local checkedItem = -1
for i, speed in ipairs(speeds) do
if speed == currentSpeed then
checkedItem = i - 1
break
end
end
speedDialog.setSingleChoiceItems(speeds, checkedItem, DialogInterface.OnClickListener{
onClick = function(dialog, which)
local selectedSpeed = speeds[which + 1]
tts.setSpeechRate(tonumber(selectedSpeed))
tts.speak("Selected speed: " .. selectedSpeed, TextToSpeech.QUEUE_FLUSH, nil, "")
savePreference("speed", selectedSpeed)
dialog.dismiss()
end
})
speedDialog.setNegativeButton("Cancel", nil)
speedDialog.show()
end)
layout.addView(speedDialogButton)
local pitchDialogButton = Button(activity)
pitchDialogButton.setText("Select Speech Pitch, Currently selected: "..getPreference("pitch", "1.0"))
pitchDialogButton.setOnClickListener(function(view)
local pitchDialog = AlertDialog.Builder(activity)
pitchDialog.setTitle("Select Speech Pitch")
local pitches = {"0.5", "0.75", "1.0", "1.25", "1.5", "1.75", "2.0"}
local currentPitch = getPreference("pitch", "1.0")
local checkedItem = -1
for i, pitch in ipairs(pitches) do
if pitch == currentPitch then
checkedItem = i - 1
break
end
end
pitchDialog.setSingleChoiceItems(pitches, checkedItem, DialogInterface.OnClickListener{
onClick = function(dialog, which)
local selectedPitch = pitches[which + 1]
tts.setPitch(tonumber(selectedPitch))
tts.speak("Selected pitch: " .. selectedPitch, TextToSpeech.QUEUE_FLUSH, nil, "")
savePreference("pitch", selectedPitch)
dialog.dismiss()
end
})
pitchDialog.setNegativeButton("Cancel", nil)
pitchDialog.show()
end)
layout.addView(pitchDialogButton)
local dialog = AlertDialog.Builder(activity)
dialog.setTitle("TTS announcement settings")
dialog.setView(layout)
dialog.setPositiveButton("OK", nil)
dialog.show()
else
showToast("No Text to Speech engines available ")
end
elseif item.getTitle() == "Clear Chat" then
d = AlertDialog.Builder(activity)
.setTitle("Clear Chat?")
.setPositiveButton("Yes", DialogInterface.OnClickListener{
onClick = function(dialog, which)
messagesContainer.removeAllViews()
table.clear(messages)
showToast("Chat has been cleared!")
end
})
.setNegativeButton("No", nil)
d.show()
elseif item.getTitle() == "Chat History" then
if #messages == 0 then
speakText("Chat history is empty!")
else
showPreviousMessages()
end
elseif item.getTitle() == "Developers" then
local dlg = AlertDialog.Builder(activity)
dlg.setTitle("Developers!")
dlg.setMessage("Developed By:\nIsmail Memon, \nUpdated by, Ayush Kumar.\n\nPlease join our Telegram Channels to grab useful Jieshuo Extension's and much more!")dlg.setPositiveButton("Join First Channel", function()local intent = Intent(Intent.ACTION_VIEW)
intent.setData(Uri.parse("https://t.me/Jieshuo_india"))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.setPackage("org.telegram.messenger")
service.startActivity(intent)
end)
dlg.setNeutralButton("Join Second Channel", function()
local intent = Intent(Intent.ACTION_VIEW)
intent.setData(Uri.parse("https://t.me/jieshuoofficial/"))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.setPackage("org.telegram.messenger")
service.startActivity(intent)
end)
dlg.setNegativeButton("Okay",nil)
dlg.show()
end
return true
end
})
popupMenu.show()
end
})
mainLayout.addView(moreOptionButton)
title = TextView(activity)
title.setText("Advance AI Pro.")
title.setTextSize(20)
title.setGravity(Gravity.CENTER)
mainLayout.addView(title)
local scrollView = ScrollView(activity)
mainLayout.addView(scrollView, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1))
messagesContainer = LinearLayout(activity)
messagesContainer.setOrientation(LinearLayout.VERTICAL)
messagesContainer.setPadding(10, 10, 10, 10)
scrollView.addView(messagesContainer, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
local msgLayout = LinearLayout(activity)
msgLayout.setOrientation(LinearLayout.HORIZONTAL)
msgLayout.setPadding(10, 10, 10, 10)
msgLayout.setGravity(Gravity.CENTER_VERTICAL)
mainLayout.addView(msgLayout, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
question = EditText(activity)
question.setHint("Message")
question.setMaxLines(4)
question.setSingleLine(false)
question.setHorizontallyScrolling(false)
question.setBackgroundColor(0xFFFFFFFF)
question.setTextColor(0xFF000000)
question.setHintTextColor(0xFF888888)
question.setPadding(10, 10, 10, 10)
msgLayout.addView(question, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1))
button = Button(activity)
button.setText("Send")
button.setBackgroundColor(0xFF6200EE)
button.setTextColor(0xFFFFFFFF)
button.setVisibility(View.GONE)
msgLayout.addView(button)
voiceButton = Button(activity)
voiceButton.setText("Talk from voice")
voiceButton.setBackgroundColor(0xFF6200EE)
voiceButton.setTextColor(0xFFFFFFFF)
voiceButton.setOnLongClickListener(View.OnLongClickListener{
onLongClick = function(view)
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
stopTTS()
if #messages == 0 then
speakText("Chat history is empty!")
else
showToast("Text to Speech stopped!")
end
return true
end
})
question.addTextChangedListener(TextWatcher{
onTextChanged = function(s, start, before, count)
local text = tostring(s)
if text:match("^%s*$") then
button.setVisibility(View.GONE)
else
button.setVisibility(View.VISIBLE)
end
end
})
button.setOnClickListener(View.OnClickListener{
onClick = function(view)
function hasInternetConnection()
local connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE)
local networkInfo = connectivityManager.getActiveNetworkInfo()
return networkInfo ~= nil and networkInfo.isConnected()
end
if not hasInternetConnection() then
showToast("Internet connection required!")
else
local questionText = question.getText().toString()
local encodedQuestion = urlEncode(questionText)
local url = "https://ayush.swarupbaral.in?msg=" .. encodedQuestion
addMessage(messagesContainer, "You:", questionText)
title.setText("AI is typing")
saveMessages()
showToast("AI is typing...")
question.setText("")
Http.get(url, function(status, data)
if status == 200 then
title.setText("Advance AI Pro.")
local cleanedData = cleanText(data)
addMessage(messagesContainer, "AI:", cleanedData)
saveMessages()
speakText(cleanedData)
showToast(cleanedData)
else
question.setText("")
title.setText("Advance AI Pro.")
local errorMessage = "An error occurred while fetching response from the AI."
addMessage(messagesContainer, "Sorry:", errorMessage)
saveMessages()
showToast(errorMessage)
end
end)
end
end
})
voiceButton.setOnClickListener(View.OnClickListener{
onClick = function(view)
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)function destroySpeechRecognizer(rec)
if rec then
rec.destroy()
rec = nil
end
end
function startSpeechRecognition()
showToast("Please speak now!")
local speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context)
local recognitionListener = RecognitionListener{
onResults = function(results)
local resultArray = results.getParcelableArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
if resultArray ~= nil and resultArray.size() > 0 then
questionText = resultArray.get(0)
local encodedQuestion = urlEncode(questionText)
local url = "https://ayush.swarupbaral.in?msg=" .. encodedQuestion
addMessage(messagesContainer, "You:", questionText)
title.setText("AI is typing")
saveMessages()
showToast("You said: " .. questionText)
Http.get(url, function(status, data)
if status == 200 then
title.setText("Advance AI Pro.")
local cleanedData = cleanText(data)
addMessage(messagesContainer, "AI:", cleanedData)
saveMessages()
speakText(cleanedData)
question.setText("")
else
question.setText("")
title.setText("Advance AI Pro.")
local errorMessage = "An error occurred while fetching response from the AI."
addMessage(messagesContainer, "Sorry:", errorMessage)
saveMessages()
showToast(errorMessage)
end
end)
end
destroySpeechRecognizer(speechRecognizer)
end,
onError = function()
showToast("I did not understand your message!")
return false
end
}
local recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, defaultLanguageCode)
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.getPackageName())
speechRecognizer.startListening(recognizerIntent)
speechRecognizer.setRecognitionListener(recognitionListener)
end
function hasInternetConnection()
local connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE)
local networkInfo = connectivityManager.getActiveNetworkInfo()
return networkInfo ~= nil and networkInfo.isConnected()
end
if not hasInternetConnection() then
showToast("Internet connection required!")
else
startSpeechRecognition()
end
end
})
msgLayout.addView(voiceButton)
activity.setContentView(mainLayout)
end
loadMessages()
function onKeyDown(code, event)
if code == 4 then
onBackButtonClick()
return true
end
return false
end
function onBackButtonClick()
local dlg = AlertDialog.Builder(activity)
dlg.setTitle("Would you like to exit?")
dlg.setNegativeButton("No",nil)
dlg.setPositiveButton("Yes", {
onClick = function(v)
activity.finish()
end
})
dlg.show()
end]]